package primaryServer

import (
	"fmt"
	"log"
	"net/rpc"
)

type Server struct {
	conn      *rpc.Client
	id        string
	port      string
	ip        string
	GameState GameState
}

type AddServerReq struct {
	Id   string
	Port string
	Ip   string
}

type AddServerRes struct {
}

func CreatePrimaryServer(conn *rpc.Client, id string, ip string, port string, K int, N int) *Server {
	server := &Server{
		conn: conn,
		id:   id,
		ip:   ip,
		port: port,
	}
	server.connectTracker()
	server.GameState = initGameState(id, K, N)

	go server.startAndListen()
	return server
}

func (s *Server) startAndListen() {
	fmt.Println("server Start And Listen")
	for {
		// listen to players action requests, respond one by one

		// reject if players actions conflict

		// update and send back latest game state if actions are legal

	}
}

// notify tracker when builing new server
func (s *Server) connectTracker() {
	req := AddServerReq{Id: s.id, Port: s.port, Ip: s.ip}
	var res AddServerRes
	err3 := s.conn.Call("Tracker.GenerateServer", req, &res)
	if err3 != nil {
		log.Fatal(err3)
	}
	fmt.Println("server generated")
}
